import 'package:get/get.dart';
import 'package:study_demo/base/BaseController.dart';

class CalculatorController extends BaseController {
  final price = '0.0'.obs;

  bool isEndWithPlusOrMinus() {
    return price.value.endsWith('-') || price.value.endsWith('+');
  }

  bool isContainPlusOrMinus() {
    return price.value.contains('+') || price.value.contains('-');
  }

  calculate() {
    if (price.value.contains('+')) {
      var index = price.value.indexOf('+');
      double price1 = double.parse(price.value.substring(0, index));
      double price2 = double.parse(price.value.substring(index + 1));
      price.value = (price1 + price2).toStringAsFixed(2);
    } else if (price.value.contains('-')) {
      var index = price.value.indexOf('-');
      double price1 = double.parse(price.value.substring(0, index));
      double price2 = double.parse(price.value.substring(index + 1));
      price.value = (price1 - price2).toStringAsFixed(2);
    } else if (price.value.contains('x')) {
      var index = price.value.indexOf('x');
      double price1 = double.parse(price.value.substring(0, index));
      double price2 = double.parse(price.value.substring(index + 1));
      price.value = (price1 * price2).toStringAsFixed(2);
    }
  }

  changePrice(String value) {
    if (price.value == '0.0') {
      if (value != '.') {
        price.value = value;
      }
    } else {
      if ((value == '.' &&
              (!price.value.contains('.') ||
                  isContainPlusOrMinus() && !isContainDotAfterPlusOrMinus())) ||
          value != '.') {
        price.value += value;
      }
    }
  }

  isContainDotAfterPlusOrMinus() {
    var index = -1;
    if (price.value.contains('+')) {
      index = price.value.indexOf('+');
    } else if (price.value.contains('-')) {
      index = price.value.indexOf('-');
    }
    return price.value.substring(index + 1).contains('.');
  }

  deletePrice() {
    if (price.value.length == 1) {
      price.value = '0.0';
    } else {
      if (price.value != '0.0') {
        price.value = price.value.substring(0, price.value.length - 1);
      }
    }
  }

  String showPriceFromDot(int type) {
    if (!price.value.contains('.')) {
      return price.value;
    }
    int index = price.value.indexOf('.');
    return type == 0
        ? price.value.substring(0, index)
        : price.value.substring(index);
  }

  clearPrice() {
    price.value = '0.0';
  }

  plus() {
    if (!isEndWithPlusOrMinus()) {
      calculate();

      price.value = price.value + '+';
    }
  }

  minus() {
    if (!isEndWithPlusOrMinus()) {
      calculate();
      price.value = price.value + '-';
    }
  }

  multiply() {
    price.value = price.value + 'x';
  }
}
